#!/usr/bin/env python3 
# -*- coding: utf-8 -*-
# @Time    : 2018/11/13 21:29
# @Author  : hyang
# @File    : flask_server.py
# @Software: python_utils

import json

from flask import Flask
from flask import request
from flask import Response

app = Flask(__name__)


# 默认是get请求
@app.route("/")
def index():
    resp = Response('<h2>首页</h2>')
    # Access - Control - Allow - Origin: *表示允许任何域名跨域访问
    resp.headers["Access-Control-Allow-Origin"] = "*"
    return resp


@app.route("/course")
def course():
    resp = Response(json.dumps({
        "name":'张三'
    }))
    resp.headers["Access-Control-Allow-Origin"] = "*"
    return resp


@app.route("/create", methods=["post",])
def create():
    print(request.form.get('name'))

    with open("user.json","r",encoding="utf-8") as f:
        data = json.loads(f.read())

    data.append({'name': request.form.get('name')})
    print(data)

    with open("user.json","w",encoding="utf-8") as f:
        f.write(json.dumps(data, ensure_ascii=False))

    resp = Response(json.dumps(data, ensure_ascii=False))
    resp.headers["Access-Control-Allow-Origin"] = "*"
    return resp


if __name__ == '__main__':
    app.run(host="localhost", port=8800,)